package br.ufu.lsi.social.storage.service;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.ufu.lsi.social.storage.model.Follow;
import br.ufu.lsi.social.storage.model.User;
import br.ufu.lsi.social.storage.repository.UserRepository;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private Neo4jTemplate template;

    
    @Transactional
    public User addUser( User user ) {  
        
        User userInDb = userRepository.findBySchemaPropertyValue( "id", user.getId() );
        if( userInDb != null )
            return userInDb;
        
        Set<Follow> followers = user.getFollowers();
        for( Follow follow : followers ) {
            grantGraphIdForAllElements( follow );
        }
        
        
        Set<Follow> friends = user.getFriends();
        for( Follow follow : friends ) {
            grantGraphIdForAllElements( follow );
        }
        
        
        return userRepository.save( user );
    }   
    
    private void grantGraphIdForAllElements( Follow follow ) {
        
        User follower = follow.getFollower();
        
        User followerInDb = userRepository.findBySchemaPropertyValue( "id", follower.getId() );
        
        if( followerInDb == null ) {
            follower = userRepository.save( follower );
        } else {
            follower = followerInDb;
        }
        follow.setFollower( follower );
        
        User followee = follow.getFollowee();
        User followeeInDb = userRepository.findBySchemaPropertyValue( "id", followee.getId() );
        
        if( followeeInDb == null ) {
            followee = userRepository.save( followee );
        } else {
            followee = followeeInDb;
        }
        follow.setFollowee( followee );
    }

}
